package com.joplus.housekeeper.network;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.CountDownTimer;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.hyphenate.chatuidemo.DemoApplication;

import com.hyphenate.chatuidemo.ui.SplashActivity;
import com.joplus.housekeeper.R;

import com.joplus.housekeeper.bean.CodeBean;

import com.joplus.housekeeper.core.Config;
import com.joplus.housekeeper.utils.AppUtils;
import com.joplus.housekeeper.utils.FileUtils;
import com.joplus.housekeeper.utils.L;
import com.joplus.housekeeper.utils.NetWorkUtils;
import com.joplus.housekeeper.utils.T;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * author： ccm
 * time： 2017/7/4.
 * description：替换asynchttp
 */

public class RetrofitHelper {

    private ApiService retrofitService = null;
    private static RetrofitHelper mInstance = null;
    private Call<ResponseBody> call;
    private final Context context;


    private RetrofitHelper() {
        context = DemoApplication.getInstance().getApplicationContext();

        OkHttpClient.Builder client = new OkHttpClient
                .Builder().connectTimeout(10, TimeUnit.SECONDS).readTimeout(10, TimeUnit.SECONDS).addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                L.e(message);
            }
        }).setLevel(HttpLoggingInterceptor.Level.BODY));/*  OkHttpClient.Builder client = new OkHttpClient
                .Builder().connectTimeout(3, TimeUnit.MINUTES).readTimeout(3, TimeUnit.MINUTES).addInterceptor(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request builder = chain.request().newBuilder().addHeader("Client-Agent", "Android").addHeader("App-Version", AppUtils.getVersionName(context) + "").addHeader("Client-Model", Build.MODEL).build();
                return chain.proceed(builder);
            }
        }).addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                L.e(message);
            }
        }).setLevel(HttpLoggingInterceptor.Level.BODY)).cookieJar(cookieManger);*/
        retrofitService = new Retrofit.Builder().baseUrl(Config.SERVICE_PATH)
                .client(client.build())

                .build().create(ApiService.class);
    }

    public static RetrofitHelper getInstance() {
        if (mInstance == null) {
            synchronized (RetrofitHelper.class) {
                if (mInstance == null) {
                    mInstance = new RetrofitHelper();
                }
            }
        }
        return mInstance;
    }

    //token过期之类的
    private void out(String message) {
        T.showLong(context, message);

        new CountDownTimer(5000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                //         cookieManger.clear();
                Intent intent = new Intent(context, SplashActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_CLEAR_TASK);

                context.startActivity(intent);
            }
        }.start();

    }

    public void get(final Context context, String url, final Class clz, final TextCallback callback) {

        if (!NetWorkUtils.isNetworkAvailable(context)) {
            callback.onFailure("network_error");
            if (context != null) {
                T.showShort(context, "网络出现错误,请检测您的网络");
            }
            return;
        }
        call = retrofitService.getWithUrl(url);
        if (call != null) {
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    ResponseBody body = response.body();
                    if (body == null) {
                        String string = "error";
                        try {
                            string = response.errorBody().string();

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        callback.onFailure(response.raw().code() + string);
                        Log.e("address", "onResponse: null body");
                        T.showShort(context, context.getString(R.string.alien_talk));
                    } else {
                        if (response.raw().code() == 200 || response.raw().code() == 201) {
                            String responseBody = "";

                            try {
                                responseBody = response.body().string();

                            } catch (Exception e) {

                                e.printStackTrace();
                                callback.onFailure(response.raw().code() + responseBody);
                                Log.e("address", "onResponse: json format");
                                T.showShort(context, context.getString(R.string.alien_talk));
                            }

                            try {
                                CodeBean accountBean = new Gson().fromJson(responseBody, CodeBean.class);
                                if ("5001".equals(accountBean.getCode())) {
                                    out(accountBean.getMessage());
                                    return;
                                }
                            } catch (Exception e) {
                            }


                            if (clz != null) {
                                Gson gson = new Gson();
                                callback.onSuccess(gson.fromJson(responseBody, clz));
                            } else {
                                callback.onSuccess(responseBody);
                            }

                        } else {
                            callback.onFailure(response.raw().code() + call.toString());
                            T.showShort(context, context.getString(R.string.alien_talk));
                            Log.e("address", "onResponse: no 200");
                        }

                    }


                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    callback.onFailure(call.toString());
                    T.showShort(context, context.getString(R.string.alien_talk));
                    Log.e("address", "onResponse: error");
                }
            });
        }
    }

    public void getFast(final Context context, String url, final Class clz, final TextCallback callback) {

        if (!NetWorkUtils.isNetworkAvailable(context)) {
            callback.onFailure("network_error");
            if (context != null) {
                T.showShort(context, "网络出现错误,请检测您的网络");
            }
            return;
        }
        call = retrofitService.getWithUrl(url);
        if (call != null) {
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    ResponseBody body = response.body();
                    if (body == null) {
                        String string = "error";
                        try {
                            string = response.errorBody().string();

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        callback.onFailure(response.raw().code() + string);
                        Log.e("address", "onResponse: null body");
                        T.showShort(context, context.getString(R.string.alien_talk));
                    } else {
                        if (response.raw().code() == 200 || response.raw().code() == 201) {
                            String responseBody = "";

                            try {
                                responseBody = response.body().string();

                            } catch (Exception e) {

                                e.printStackTrace();
                                callback.onFailure(response.raw().code() + responseBody);
                                Log.e("address", "onResponse: json format");
                                T.showShort(context, context.getString(R.string.alien_talk));
                            }

                            try {

                                CodeBean accountBean = new Gson().fromJson(responseBody, CodeBean.class);
                                if ("5001".equals(accountBean.getCode())) {
                                    out(accountBean.getMessage());
                                    return;
                                }
                            } catch (Exception e) {
                            }


                            if (clz != null) {
                                Gson gson = new Gson();

                                callback.onSuccess(JSON.parseObject(responseBody, clz));
                            } else {
                                callback.onSuccess(responseBody);
                            }

                        } else {
                            callback.onFailure(response.raw().code() + call.toString());
                            T.showShort(context, context.getString(R.string.alien_talk));
                            Log.e("address", "onResponse: no 200");
                        }

                    }


                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    callback.onFailure(call.toString());
                    T.showShort(context, context.getString(R.string.alien_talk));
                    Log.e("address", "onResponse: error");
                }
            });
        }
    }

    public void downLoad(String url, final File file, final TextCallback callback) {


        if (!NetWorkUtils.isNetworkAvailable(context)) {
            callback.onFailure("network_error");
            if (context != null) {
                T.showShort(context, "网络出现错误,请检测您的网络");
            }
            return;
        }
        call = retrofitService.downLoad(url);
        if (call != null) {
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    ResponseBody body = response.body();
                    if (body == null) {
                        String string = "error";
                        try {
                            string = response.errorBody().string();

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        callback.onFailure(response.raw().code() + string);
                        T.showShort(context, context.getString(R.string.alien_talk));
                    } else {
                        if (response.raw().code() == 200 || response.raw().code() == 201) {
                            FileUtils.writeFile2Disk(response, file, callback);
                        } else {
                            callback.onFailure(response.raw().code() + call.toString());
                            T.showShort(context, context.getString(R.string.alien_talk));

                        }

                    }


                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    callback.onFailure(call.toString());
                    T.showShort(context, context.getString(R.string.alien_talk));

                }
            });
        }
    }

    public void post(String url, Map<String, Object> map, final Class clz, final TextCallback callback) {

        if (!NetWorkUtils.isNetworkAvailable(context)) {
            callback.onFailure("network_error");
            if (context != null) {
                T.showShort(context, "网络出现错误,请检测您的网络");
            }
            return;
        }

        call = retrofitService.postWithMap(url, map);

        if (call != null) {
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    Gson gson = new Gson();
                    ResponseBody body = response.body();
                    if (body == null) {
                        String string = "error";
                        try {
                            string = response.errorBody().string();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        callback.onFailure(response.raw().code() + string);
                        T.showShort(context, context.getString(R.string.alien_talk));
                        Log.e("http-error", "onResponse:  body null");
                    } else {
                        if (response.raw().code() == 200 || response.raw().code() == 201) {
                            String responseBody = "";
                            try {
                                responseBody = response.body().string();
                            } catch (Exception e) {
                                callback.onFailure(response.raw().code() + responseBody);
                                T.showShort(context, context.getString(R.string.alien_talk));
                                Log.e("http-error", "onResponse:  body 解析报错");
                            }
                            try {
                                JSONObject jsonObject = new JSONObject(responseBody);
                                if ("5001".equals(jsonObject.getString("code"))) {
                                    out(jsonObject.getString("message"));
                                    return;
                                }
                            } catch (Exception e) {

                            }
                            if (clz != null) {

                                callback.onSuccess(gson.fromJson(responseBody, clz));
                            } else {
                                callback.onSuccess(responseBody);
                            }

                        } else {
                            callback.onFailure(response.raw().code() + call.toString());
                            T.showShort(context, context.getString(R.string.alien_talk));
                            Log.e("http-error", "onResponse:  fei 200");

                        }

                    }


                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    callback.onFailure(call.toString());
                    T.showShort(context, context.getString(R.string.alien_talk));
                    Log.e("http-error", "onResponse:  failuser" + call + t.toString());

                }
            });
        }
    }

    public void postNoMap(String url, final Class clz, final TextCallback callback) {

        if (!NetWorkUtils.isNetworkAvailable(context)) {
            callback.onFailure("network_error");
            if (context != null) {
                T.showShort(context, "网络出现错误,请检测您的网络");
            }
            return;
        }

        call = retrofitService.post(url);

        if (call != null) {
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    Gson gson = new Gson();
                    ResponseBody body = response.body();
                    if (body == null) {
                        String string = "error";
                        try {
                            string = response.errorBody().string();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        callback.onFailure(response.raw().code() + string);
                        T.showShort(context, context.getString(R.string.alien_talk));
                        Log.e("http-error", "onResponse:  body null");
                    } else {
                        if (response.raw().code() == 200 || response.raw().code() == 201) {
                            String responseBody = "";
                            try {
                                responseBody = response.body().string();
                            } catch (Exception e) {
                                callback.onFailure(response.raw().code() + responseBody);
                                T.showShort(context, context.getString(R.string.alien_talk));
                                Log.e("http-error", "onResponse:  body 解析报错");
                            }
                            try {
                                JSONObject jsonObject = new JSONObject(responseBody);
                                if ("5001".equals(jsonObject.getString("code"))) {
                                    out(jsonObject.getString("message"));
                                    return;
                                }
                            } catch (Exception e) {

                            }
                            if (clz != null) {

                                callback.onSuccess(gson.fromJson(responseBody, clz));
                            } else {
                                callback.onSuccess(responseBody);
                            }

                        } else {
                            callback.onFailure(response.raw().code() + call.toString());
                            T.showShort(context, context.getString(R.string.alien_talk));
                            Log.e("http-error", "onResponse:  fei 200");

                        }

                    }


                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    callback.onFailure(call.toString());
                    T.showShort(context, context.getString(R.string.alien_talk));
                    Log.e("http-error", "onResponse:  failuser" + call + t.toString());

                }
            });
        }
    }

    public void postFile(String url, MultipartBody.Part body, final Class clz, final TextCallback callback) {

        if (!NetWorkUtils.isNetworkAvailable(context)) {
            callback.onFailure("network_error");
            if (context != null) {
                T.showShort(context, "网络出现错误,请检测您的网络");
            }
            return;
        }

        call = retrofitService.postWithFile(url, body);

        if (call != null) {
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    Gson gson = new Gson();
                    ResponseBody body = response.body();
                    if (body == null) {
                        String string = "error";
                        try {
                            string = response.errorBody().string();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        callback.onFailure(response.raw().code() + string);
                        T.showShort(context, context.getString(R.string.alien_talk));
                        Log.e("http-error", "onResponse:  body null");
                    } else {
                        if (response.raw().code() == 200 || response.raw().code() == 201) {
                            String responseBody = "";
                            try {
                                responseBody = response.body().string();
                            } catch (Exception e) {
                                callback.onFailure(response.raw().code() + responseBody);
                                T.showShort(context, context.getString(R.string.alien_talk));
                                Log.e("http-error", "onResponse:  body 解析报错");
                            }
                            try {
                                JSONObject jsonObject = new JSONObject(responseBody);
                                if ("5001".equals(jsonObject.getString("code"))) {
                                    out(jsonObject.getString("message"));
                                    return;
                                }
                            } catch (Exception e) {

                            }
                            if (clz != null) {

                                callback.onSuccess(gson.fromJson(responseBody, clz));
                            } else {
                                callback.onSuccess(responseBody);
                            }

                        } else {
                            callback.onFailure(response.raw().code() + call.toString());
                            T.showShort(context, context.getString(R.string.alien_talk));
                            Log.e("http-error", "onResponse:  fei 200");

                        }

                    }


                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    callback.onFailure(call.toString());
                    T.showShort(context, context.getString(R.string.alien_talk));
                    Log.e("http-error", "onResponse:  failuser" + call + t.toString());

                }
            });
        }
    }

    public void postFile(String url, Map<String, RequestBody> param, MultipartBody.Part body, final Class clz, final TextCallback callback) {

        if (!NetWorkUtils.isNetworkAvailable(context)) {
            callback.onFailure("network_error");
            if (context != null) {
                T.showShort(context, "网络出现错误,请检测您的网络");
            }
            return;
        }

        call = retrofitService.postWithFile(url, body, param);

        if (call != null) {
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    Gson gson = new Gson();
                    ResponseBody body = response.body();
                    if (body == null) {
                        String string = "error";
                        try {
                            string = response.errorBody().string();
                        } catch (IOException e) {
                            e.printStackTrace();
                            Log.e("http-error", "onResponse: " + e.toString());
                        }
                        callback.onFailure(response.raw().code() + string);
                        T.showShort(context, context.getString(R.string.alien_talk));
                        Log.e("http-error", "onResponse:  body null");
                    } else {
                        if (response.raw().code() == 200 || response.raw().code() == 201) {
                            String responseBody = "";
                            try {
                                responseBody = response.body().string();
                            } catch (Exception e) {
                                callback.onFailure(response.raw().code() + responseBody);
                                T.showShort(context, context.getString(R.string.alien_talk));
                                Log.e("http-error", "onResponse:  body 解析报错");
                            }
                            try {
                                JSONObject jsonObject = new JSONObject(responseBody);
                                if ("5001".equals(jsonObject.getString("code"))) {
                                    out(jsonObject.getString("message"));
                                    return;
                                }
                            } catch (Exception e) {

                            }
                            if (clz != null) {

                                callback.onSuccess(gson.fromJson(responseBody, clz));
                            } else {
                                callback.onSuccess(responseBody);
                            }

                        } else {
                            callback.onFailure(response.raw().code() + call.toString());
                            T.showShort(context, context.getString(R.string.alien_talk));
                            Log.e("http-error", "onResponse:  fei 200");

                        }

                    }


                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    callback.onFailure(call.toString());
                    T.showShort(context, context.getString(R.string.alien_talk));
                    Log.e("http-error", "onResponse:  failuser" + call + t.toString());

                }
            });
        }
    }

    public void delete(Context context, String url, final Class clz, final TextCallback callback) {


        if (!NetWorkUtils.isNetworkAvailable(context)) {
            callback.onFailure("network_error");
            if (context != null) {
                T.showShort(context, "网络出现错误,请检测您的网络");
            }
            return;
        }
        call = retrofitService.getWithUrl(url);
        if (call != null) {
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    ResponseBody body = response.body();
                    if (body == null) {
                        String string = "error";
                        try {
                            string = response.errorBody().string();

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        callback.onFailure(response.raw().code() + string);

                    } else {
                        if (response.raw().code() == 200 || response.raw().code() == 201) {
                            String responseBody = "";
                            try {
                                responseBody = response.body().string();

                            } catch (IOException e) {
                                e.printStackTrace();
                                callback.onFailure(response.raw().code() + responseBody);

                            }
                            if (clz != null) {
                                Gson gson = new Gson();
                                callback.onSuccess(gson.fromJson(responseBody, clz));
                            } else {
                                callback.onSuccess(responseBody);
                            }

                        } else {
                            callback.onFailure(response.raw().code() + call.toString());

                        }

                    }


                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    callback.onFailure(call.toString());

                }
            });
        }
    }


}